<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item> <i class="el-icon-lx-cascades"></i> 用户管理 </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <el-button type="primary" icon="el-icon-delete" class="handle-del mr10" @click="delAllSelection">批量删除</el-button>
                <el-select v-model="query.roleId" placeholder="角色" class="handle-select mr10">
                    <!-- 下面这里需要使用这个for循环来赋值这个数据了 -->
                    <el-option v-for="(role, index) of roleList" :key="index" :label="role.roleDes" :value="role.roleId"></el-option>
                </el-select>
                <el-input v-model="query.realName" placeholder="用户名" class="handle-input mr10"></el-input>
                <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
                <el-button type="primary" icon="el-icon-lx-add" @click="handlerAdd">添加</el-button>
            </div>
            <el-table
                :data="tableData"
                border
                class="table"
                ref="multipleTable"
                header-cell-class-name="table-header"
                @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="55" align="center"></el-table-column>
                <el-table-column prop="userId" label="ID" width="55" align="center"></el-table-column>
                <el-table-column prop="username" align="center" label="用户名"></el-table-column>
                <el-table-column prop="realName" align="center" label="真实名字"></el-table-column>

                <el-table-column label="性别" align="center">
                    <!--这个就相当于是遍历一行的数据
                        这个scope.row就相当于每一次遍历的user
                    -->
                    <template slot-scope="scope">
                        <!-- 这里需要一个展示文本的组件 -->
                        <el-tag>{{ scope.row.sex == '0' ? '男' : scope.row.sex == '1' ? '女' : '其他' }}</el-tag>
                    </template>
                </el-table-column>

                <el-table-column prop="weixin" align="center" label="微信"></el-table-column>
                <el-table-column prop="qq" width="100" align="center" label="QQ"></el-table-column>
                <el-table-column prop="age" align="center" label="年龄"></el-table-column>
                <el-table-column prop="subjectName" align="center" label="学科"></el-table-column>
                <el-table-column prop="schoolName" align="center" label="学校"></el-table-column>
                <el-table-column prop="lastLoginTime" align="center" label="登陆时间"></el-table-column>
                <!-- <el-table-column label="类型" align="center">
                    <template slot-scope="scope">
                        <el-tag
                            :type="scope.row.state==='成功'?'success':(scope.row.state==='失败'?'danger':'')"
                        >{{scope.row.state}}</el-tag>
                    </template>
                </el-table-column> -->
                <el-table-column width="120" label="头像(查看大图)" align="center">
                    <!--这个就相当于是遍历一行的数据
                        这个scope.row就相当于每一次遍历的user
                    -->
                    <template slot-scope="scope">
                        <el-image class="table-td-thumb" :src="scope.row.photo" :preview-src-list="[scope.row.photo]"></el-image>
                    </template>
                </el-table-column>

                <el-table-column label="操作" width="180" align="center">
                    <template slot-scope="scope">
                        <el-button type="text" icon="el-icon-edit" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                        <el-button type="text" icon="el-icon-delete" class="red" @click="handleDelete(scope.$index, scope.row)"
                            >删除</el-button
                        >
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页的组件 -->
            <div class="pagination">
                <el-pagination
                    background
                    layout="total, prev, pager, next"
                    :current-page="query.pageIndex"
                    :page-size="query.pageSize"
                    :total="pageTotal"
                    @current-change="handlePageChange"
                ></el-pagination>
            </div>
        </div>

        <!-- 编辑弹出框 -->
        <el-dialog title="编辑" :visible.sync="editVisible" width="50%">
            <el-form ref="form" :model="form" label-width="70px">
                <el-row>
                    <el-col :span="10">
                        <el-form-item label="用户名">
                            <el-input v-model="user.username"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10">
                        <el-form-item label="密码" label-width="100px">
                            <el-input v-model="user.password"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="10">
                        <el-form-item label="名字">
                            <el-input v-model="user.realName"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10">
                        <el-form-item label="年龄" label-width="100px">
                            <el-input v-model="user.age"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="10">
                        <el-form-item label="电话">
                            <el-input v-model="user.telPhone"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10">
                        <el-form-item label="微信" label-width="100px">
                            <el-input v-model="user.weixin"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="10">
                        <el-form-item label="学校">
                            <el-select v-model="user.schoolId" placeholder="请选择">
                                <el-option key="bbk" label="不属于学校" value="-1"></el-option>
                                <el-option
                                    v-for="(school, index) of schoolList"
                                    :key="index"
                                    :label="school.schoolName"
                                    :value="school.schoolId"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10">
                        <el-form-item label="学科" label-width="100px">
                            <el-select v-model="user.subjectId" placeholder="请选择">
                                <el-option key="bbk" label="不属于学科" value="-1"></el-option>
                                <el-option
                                    v-for="(subject, index) of subjectList"
                                    :key="index"
                                    :label="subject.subjectName"
                                    :value="subject.subjectId"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-form-item label="QQ">
                    <el-input style="width: 400px" v-model="user.qq"></el-input>
                </el-form-item>

                <el-form-item label="性别">
                    <el-radio v-model="user.sex" label="0">男</el-radio>
                    <el-radio v-model="user.sex" label="1">女</el-radio>
                    <el-radio v-model="user.sex" label="2">其他</el-radio>
                </el-form-item>

                 <el-form-item label="头像">
                        <el-upload
                            class="avatar-uploader"
                            :show-file-list="false"
                            :auto-upload="false"
                            action=""
                            :on-change="fileChange"
                            :on-success="handleAvatarSuccess"
                            :before-upload="beforeAvatarUpload"
                        >
                            <img width="178" v-if="imageUrl" :src="imageUrl" class="avatar" />
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                            <div>请上传jpg或者png的图片</div>
                        </el-upload>
                    </el-form-item> 

                <el-form-item label="角色">
                    <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
                    <div style="margin: 15px 0"></div>
                    <el-checkbox-group v-model="roleIds" @change="handleCheckedCitiesChange">
                        <el-checkbox v-for="role in roleList1" :label="role.roleId" :key="role.roleId">{{ role.roleDes }}</el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
            </el-form>

            <span slot="footer" class="dialog-footer">
                <el-button @click="cancelEdit">取 消</el-button>
                <el-button type="primary" @click="saveEdit">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
const cityOptions = ['上海', '北京', '广州', '深圳'];

import { fetchData } from '../../api/index';
export default {
    name: 'basetable',
    data() {
        return {
            roleIds:[],
            roleList: [],
            user: {},
            query: {
                roleId: '',
                realName: '',
                pageIndex: 1,
                pageSize: 10
            },
            imageUrl: '',
            roleList1: [],
            schoolList: [],
            subjectList: [],
            tableData: [],
            multipleSelection: [],
            delList: [],
            editVisible: false,
            pageTotal: 0,
            form: {},
            idx: -1,
            id: -1,
            checkAll: false,
            checkedCities: ['上海', '北京'],
            cities: cityOptions,
            isIndeterminate: true,
            backData: {},
            file: []
        };
    },
    // from ：从哪里来  to：到哪里去  next执行的函数
    beforeRouteEnter(to, from, next) {
        //这里面是没法直接使用this 路由进入的时候 这个this对象可能都还不存在
        //所以不能直接使用this
        next((vm) => {
            vm.getData();
            vm.initRole();
            vm.initSchoolSubjectRole();
        });
    },
    // created() {
    //     //这个生命周期的勾子函数只会执行一次
    //     //需要换一个生命周期的勾子函数
    //     this.getData();
    //     this.initRole();
    // },
    methods: {
        cancelEdit() {
            //之前还需要将数据还原
            this.$set(this.tableData, this.idx, this.backData);
            this.editVisible = false;
        },
        handleCheckAllChange(val) {
            this.checkedCities = val ? cityOptions : [];
            this.isIndeterminate = false;
        },
        handleCheckedCitiesChange(value) {
            let checkedCount = value.length;
            this.checkAll = checkedCount === this.roleList.length;
            this.isIndeterminate = checkedCount > 0 && checkedCount < this.roleList.length;
        },
        handleAvatarSuccess(res, file) {
            this.imageUrl = URL.createObjectURL(file.raw);
        },
        fileChange(file, fileList) {
            //只要文件的内容发生改变 那么这里就将文件的内容复制给这个对象
            this.file = file.raw;
            this.imageUrl = URL.createObjectURL(this.file);
        },
        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        },

        initSchoolSubjectRole() {
            this.$axios.get('/api/useraddservice/useradds/addUserInit.action').then(
                (resp) => {
                    if (!resp.data.code) {
                        this.schoolList = resp.data.dataMap.schoolList;
                        this.roleList1 = resp.data.dataMap.roleList;
                        this.subjectList = resp.data.dataMap.subjectList;
                    } else {
                        this.$message.error('初始化数据失败...');
                    }
                },
                (error) => {
                    this.$message.error('初始化数据失败...:' + error.message);
                }
            );
        },
        initRole() {
            //发送请求到服务器去获取所有的角色
            this.$axios.get('/api/roleservice/roles/list.action').then(
                (resp) => {
                    if (!resp.data.code) {
                        this.roleList = resp.data.dataMap.roleList;
                    } else {
                        this.$message.error('初始化角色数据失败...');
                    }
                },
                (error) => {
                    this.$message.error('初始化角色数据失败...:' + error.message);
                }
            );
        },
        handlerAdd() {
            //这里要编写这个编程式路由 向UserAdd页面进行跳转
            this.$router.push({
                name: 'addUser'
            });
        },
        // 获取 easy-mock 的模拟数据
        getData() {
            //这里就应该发送请求到服务器去获取数据
            this.$axios.post('/api/userservice/users/list.action', this.query).then(
                (resp) => {
                    if (!resp.data.code) {
                        //说明请求成功...
                        this.tableData = resp.data.dataMap.userList;
                        this.pageTotal = resp.data.dataMap.total;
                    } else {
                        this.$message.error('初始化数据失败..');
                    }
                },
                (error) => {
                    this.$message.error('初始化数据失败..:' + error.message);
                }
            );
        },
        // 触发搜索按钮
        handleSearch() {
            this.$set(this.query, 'pageIndex', 1);
            this.getData();
        },
        // 删除操作
        // 第一个参数：就是当前的用户对象在数组中的下标...
        // 第二个参数: 就是当前的用户对象
        handleDelete(index, row) {
            // 二次确认删除
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            })
                .then(() => {
                    //我们写代码应该写到这里....
                    //向服务器发送删除请求
                    this.$axios.get('/api/userservice/users/deleteById.action?userId=' + row.userId).then(
                        (resp) => {
                            if (!resp.data.code) {
                                this.$message.success('删除成功');
                                this.tableData.splice(index, 1);
                            } else {
                                this.$message.error('删除数据失败...');
                            }
                        },
                        (error) => {
                            this.$message.error('删除数据失败...:' + error.message);
                        }
                    );
                })
                .catch(() => {});
        },
        // 多选操作
        //多选操作  每一次选择项发生改变都会触发这个函数
        // val：目前为止 还处于 选中状态下的所有的数据组成的数组
        handleSelectionChange(val) {
            //他将这个改变的数据赋值给了一个数组
            this.multipleSelection = val;
        },

        //批量删除数据的按钮触发的函数
        delAllSelection() {
            //this.multipleSelection：选中数据的集合
            const length = this.multipleSelection.length;
            let str = '';
            //这个表示的是将原来数组的数据 copy到一个新的数组中来...
            this.delList = this.delList.concat(this.multipleSelection);
            //写了个循环
            for (let i = 0; i < length; i++) {
                // this.multipleSelection[i] 这个每一个元素 其实就是每一个选中的每一个用户对象...
                str += this.multipleSelection[i].userId + ' ';
            }
            this.$message.error(`删除了${str}`);
            //接下来就应该发送请求到服务器去删除这个数据
            this.$axios
                .get('/api/userservice/users/deleteByIds.action', {
                    params: {
                        userIds: str
                    }
                })
                .then(
                    (resp) => {
                        if (!resp.data.code) {
                            //这里是成功
                            this.multipleSelection = [];
                            this.getData();
                        } else {
                            //这里是失败
                            this.$message.error('删除数据失败..');
                        }
                    },
                    (error) => {
                        this.$message.error('删除数据失败..:' + error.message);
                    }
                );
        },
        // 编辑操作
        handleEdit(index, row) {
            //在这里还需要将原始数据进行深拷贝...
            this.backData = { ...row };
            //这里记录下标的目的是为了还原数据
            this.idx = index;
            console.log('----------:' + row.subjectId);
            if (row.subjectId == undefined) {
                row.subjectId = '-1';
            }
            if (row.schoolId == undefined) {
                row.schoolId = '-1';
            }
            this.imageUrl = row.photo;
            //这里需要处理下这个性别
            row.sex = row.sex.toString();
            this.user = row;
            //所以接下来就应该将这个用户所具有的这个角色查询出来然后赋值给他
            //说白了 就是通过用户id查询用户具有的角色id
            this.$axios
                .get('/api/roleservice/roles/listRoleIdByUserId.action', {
                    params: {
                        userId: row.userId
                    }
                })
                .then(
                    (resp) => {
                        if (!resp.data.code) {
                            this.roleIds = resp.data.dataMap.roleIds;
                            this.editVisible = true;
                        } else {
                            this.$message.error('通过用户id查询角色id失败...');
                        }
                    },
                    (error) => {
                        this.$message.error('通过用户id查询角色id失败...:' + error.message);
                    }
                );
        },
        // 保存编辑
        saveEdit() {
            //这里就需要发送请求到服务器更新数据

            //这里需要添加用户
            //这里需要使用表单进行上传(上传的既有图片还有文字)
            //首先是要准备数据
            var form1 = new FormData();

            console.log("---------------"+this.file.length)
            //接下来向里面放数据
            if(this.file.length!=0){
                form1.append('file', this.file, this.file.name);
            }
            form1.append('userId', this.user.userId);
            form1.append('username', this.user.username);
            form1.append('password', this.user.password);
            form1.append('realName', this.user.realName);
            form1.append('telPhone', this.user.telPhone);
            form1.append('weixin', this.user.weixin);
            form1.append('qq', this.user.qq);
            form1.append('subjectId', this.user.subjectId);
            form1.append('schoolId', this.user.schoolId);
            form1.append('roleIds', this.roleIds);
            form1.append('age', this.user.age);
            form1.append('sex', this.user.sex);
            //接下来就是使用axios来上传这个数据
            this.$axios({
                method: 'POST',
                url: '/api/userservice/users/updateUser.action',
                data: form1,
                header: {
                    'Content-Type': 'multipart/form-data' //这个叫做以表单的形式上传数据
                }
            }).then(
                (resp) => {
                    if (!resp.data.code) {
                        this.$message.success('更新成功！');
                        this.editVisible = false;
                        this.$message.success(`修改第 ${this.idx + 1} 行成功`);
                        //this.$set(this.tableData, this.idx, this.form);
                        this.getData();
                    }else{
                        this.$message.error('更新失败！');
                    }
                },
                (error) => {
                    this.$message.error('更新失败！:'+error.message);
                }
            );
        },

        // 分页导航
        handlePageChange(val) {
            //下面表示的是给 vue中的这个query对象 设置pageIndex的属性的值 为当前页码
            this.$set(this.query, 'pageIndex', val);
            this.getData();
        }
    }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
</style>
